#!/usr/bin/perl
# Tail -f equivalent for the f_log database table
#
use Counter;
# must use counter to get .counter.ini read properly
use Carp;
use Getopt::Long;

$| = 1;
$argtof = 10; # Number of lines to go back in log
$blocksize = 200; # Max number to get in one select

GetOptions("lines=i" => \$argtof,
	   "blocksize=i" => \$blocksize,
	   );

FileTable::dbconnect() if !$FileTable::dbhandle;
my $dbhandle = $FileTable::dbhandle;

my $stm = $dbhandle->prepare("select max(uniqueid) from f_log");
my $status = $stm->execute();
my @elm = $stm->fetchrow_array();
$lastu = $elm[0] - $argtof;
warn "Starting from $lastu\n";

while (1) {
    @recs = taillog($lastu);
    for $rec (@recs) {
	$lastu = $$rec{uniqueid} if $$rec{uniqueid} > $lastu;
	if ($$rec{tablename} ne "email") {
	    printf "%s: %6.6s %-8s %-8s %-30.30s %s\n",
	    $$rec{date}, $$rec{operation}, $$rec{tablename}, $$rec{reckey},
	    interestingdata($$rec{tablename}, $$rec{data}),
	    $$rec{authority};
	} else {
	    printf "%s: %6.6s %-8s %-24.24s %-14.14s %s\n",
	    $$rec{date}, $$rec{operation}, $$rec{tablename}, $$rec{reckey},
	    interestingdata($$rec{tablename}, $$rec{data}),
	    $$rec{authority};
	}
    }
    sleep 5;
}

sub taillog {
    my $lastuniq = shift;
    my $elm;
    my @results;
    

    my $stm = $dbhandle->prepare("SELECT uniqueid, tablename, reckey, operation, data, date, authority FROM f_log WHERE uniqueid > ? ORDER BY uniqueid LIMIT $blocksize");
    my $status = $stm->execute($lastuniq);

    if (!$status) {
	croak "Log error: " . $stm->errstr;
    }
    while ($elm = $stm->fetchrow_hashref()) {
        push(@results, $elm);
    }
    return @results;
}

sub interestingdata {
    my $table = shift;
    my $rectext = shift;
    my $fakefile = {};

    bless $fakefile, "FileTable";

    my $rec = $fakefile->makeobject("nokey", $rectext);
    if ($table eq "users") {
	return "state:$$rec{state}";
    } elsif ($table eq "machines") {
	return "$$rec{owner} $$rec{name} - $$rec{cpu}";
    } elsif ($table eq "persons") {
	return "$$rec{country} $$rec{name}";
    } elsif ($table eq "email") {
	# this is presented in a short field...
	return "$$rec{owner} $$rec{state}";
    } elsif ($table eq "places") {
	if ($$rec{type} eq "alias") {
	    return "$$rec{name} alias within $$rec{within}";
	} elsif ($$rec{type} eq "city") {
	    return "$$rec{name}  $$rec{users}";
	} else {
	    return "$$rec{name} $$rec{type} $$rec{users}";
	}
    } elsif ($table eq "frozen") {
	return "$$rec{owner} $$rec{ftable} $$rec{fkey}";
    } else {
	return "nothing for table $table";
    }
}

